$(document).ready(function(){
	function updateAvatars(url) {
		showAvatars();
		$(".big-avatar").attr("src", url);
		$.messager.show('提示', '更新头像成功。', 5000);
	}

	$(document).on("click",".profile-box-avatar-select",function(){
		var provider = $(this).attr("provider");
		var url = $(this).children("img").attr("src");
		$.post("/api/avatar/modify", { url: url} ,function(data){
			updateAvatars(url);
		});
	});

	function showAvatars() {
		$.post("/api/avatar", { } ,function(data){
			if (data.code === 200) {
				$(".avatar-list").html("");
				var avatars = data.data;
				var html = "";
				for ( var i = 0; i < avatars.length; i++) {
					html += "<div class=\"profile-box-avatar-select profile-box-avatar-avatar\" provider=\""+avatars[i].provider+"\">";
					html += "<img class=\"small-avatar\" src=\""+ avatars[i].avatar_url +"\" >";
					html += "<span class=\"avatar-provider\">" + avatars[i].provider + "</span>";
					if (avatars[i].selected) {
						html += "<span class=\"avatar-check-select avatar-selected\"></span>";
					} else {
						html += "<span class=\"avatar-check-select\"></span>";
					}
					html += "</div>";
				}
				$(".avatar-list").html(html);
			}
		});
	}
	$("a.photo-change").click(function() {
		showAvatars();
		$(".profile-box-avatar-change").fadeIn();
	});
	$("a.profile-box-avatar-upload-cancel").click(function() {
		$(".profile-box-avatar-change").fadeOut();
	});
	document.addEventListener('click', function(event) {
		var div = document.getElementById('profile-box-avatar-change');
		var div2 = document.getElementById('photo-change');
		var div3 = document.getElementById('pop-div-photo');
		var div4 = document.getElementById('pop-inner-div-photo');
		if (event.target !== div && !div.contains(event.target)
			&& div2 !== event.target && div3 !== event.target && div4 !== event.target) {
			$(".profile-box-avatar-change").fadeOut();
		}
	});

	$("a.photo").click(function() {
		document.documentElement.style.overflowY = 'hidden';

		$(".pop-div-photo").fadeIn(); 
		$(".pop-inner-div-photo").fadeIn(); 
		return false;
	});

	function closeUploadPhotoWindow(){
		$(".pop-div-photo").fadeOut();
		$(".pop-inner-div-photo").fadeOut();
		document.documentElement.style.overflowY = 'scroll';
	}
	$(".pop-div-photo").click(function(){
		closeUploadPhotoWindow();
	});
	
	function getSize(size){
		var num=parseInt(size);
		if(num<=300){
			return num;
		}
		return getSize(num/2);
	}
	
	function getRoundedCanvas(sourceCanvas) {
		var canvas = document.createElement('canvas');
		var context = canvas.getContext('2d');
		var width = sourceCanvas.width;
		var height = sourceCanvas.height;
		width=getSize(width);
		height=width;
		canvas.width = width;
		canvas.height = height;
		context.beginPath();
		context.arc(width/2, height/2, Math.min(width, height)/2, 0, 2 * Math.PI);
		context.strokeStyle = 'rgba(0,0,0,0)';
		context.stroke();
		context.clip();
		context.drawImage(sourceCanvas, 0, 0, width, height);
		return canvas;
	}

	var image = document.getElementById('img-photo');
	var cropper, canvas;
	$('#file-avatar').change(function(e) {
	    if (cropper) {
	        cropper.destroy();
	    }
	    var file;
	    var files = e.target.files;
	    if (files && files.length > 0) {
	        file = URL.createObjectURL(files[0]);
	        $('#img-photo').attr({ 'src': file })
	    }
	    cropper = new Cropper(image, {
	        aspectRatio: 1,
	        viewMode: 1,
	        background: true, //�Ƿ���ʾ���񱳾�
	        zoomable: true,   //�Ƿ�����Ŵ�ͼ��
	        guides: true,     //�Ƿ���ʾ�ü�������
	        crop: function(event) { //���ÿ����仯ִ�еĺ�����
	            canvas = cropper.getCroppedCanvas({
	                minWidth: 200,
				    minHeight: 200,
					maxWidth: 400,
					maxHeight: 400,
	                imageSmoothingEnabled: true,
	  				imageSmoothingQuality: 'high',
	            });
	            
	            roundedCanvas = getRoundedCanvas(canvas);
	            $('#imga-preview').attr("src", roundedCanvas.toDataURL("image/png", 1))
	            $('#imga-preview80').attr("src", roundedCanvas.toDataURL("image/png", 1))
	            $('#imga-preview50').attr("src", roundedCanvas.toDataURL("image/png", 1))
	        }
	    });
	});

	$('#file-avatar').on("change",function() {
		var i = $(this).next('label').clone();
		var file = $('#file-avatar')[0].files[0].name;
		$(this).next('label').text(file);
	});

	$('button.btn-avatar-upload').click(function() {
	    var file = dataURLtoBlob($('#imga-preview').attr("src"));
	    var newImg = new Date().getTime() + '.png';
	    var formData = new FormData();
	    formData.append('photo', file, newImg)
		$.ajax({
	        type: "POST",
	        url: "/api/avatar/upload",
	        data: formData,
	        processData: false,
	        contentType: false,
	        success: function(data) {
	            var data = data;
				closeUploadPhotoWindow();
				updateAvatars(data.data);
	        },
	        error: function (data) {
	        	alert("upload failed.");
			}
	    })
	})

	function dataURLtoBlob(dataurl) {
	    var arr = dataurl.split(','),
	        mime = arr[0].match(/:(.*?);/)[1],
	        bstr = atob(arr[1]),
	        n = bstr.length,
	        u8arr = new Uint8Array(n);
	    while (n--) {
	        u8arr[n] = bstr.charCodeAt(n);
	    }
	    return new Blob([u8arr], { type: mime });
	}

});